package com.cavedroid;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;

import javax.microedition.khronos.opengles.GL10;

public class ExtendableShape {
	
	private ByteBuffer byteBuffer;
	
	protected FloatBuffer buffer;
	
	private int size;
	
	protected int secondHalfSize;
	
	public int splitPoint = 0;
	
	protected int tempPoint = 0;
	
	public int gap;
	
	private int fullSize;
	
	private int fullGapSize;
	
	public int dimensions;
	
	public float[] tempVertex;
	
	public int continuingVerts;
	
	public ExtendableShape(int length, int blockSize, int cVerts, int dims) {
		size = length+1;
		secondHalfSize = length*blockSize;
		gap = blockSize;
		dimensions = dims;
		
		fullGapSize = gap*dimensions;
		fullSize = size*fullGapSize;
		
		byteBuffer = ByteBuffer.allocateDirect((fullSize+cVerts*dimensions)*(Float.SIZE/8));
		byteBuffer.order(ByteOrder.nativeOrder());
		buffer = byteBuffer.asFloatBuffer();
		
		continuingVerts = cVerts;
		tempVertex = new float[dims];
	}
	
	public float[] get(int index) {
		int start;
		start = splitPoint+gap+index;
		if (start > size*gap) {
			start = index - secondHalfSize;
		}
		for (int i = 0; i < dimensions; i++) {
			tempVertex[i] = buffer.get(start*dimensions + i);
		}
		return tempVertex;
	}
	
	public void offer(int index, float[] o) {
		//buffer.position(tempPoint);
		//buffer.put(o, index, dimensions);
		for (int i = 0; i < dimensions; i++) {
			buffer.put(tempPoint+i, o[index+i]);
		}
		tempPoint += dimensions;
		if (tempPoint % fullGapSize == 0) {
			//Create continuing vertex
			for (int i = 0; i < dimensions*continuingVerts; i++) {
				buffer.put(fullSize+i, buffer.get(i));
			}
		
			splitPoint += gap;
			secondHalfSize -= gap;
			tempPoint = splitPoint*dimensions;
			if (splitPoint >= size*gap) {
				tempPoint = 0;
				splitPoint = 0;
				secondHalfSize = (size-1)*gap;
			}
		}
		//buffer.rewind();
	}
	
	public void offer(float[] o) {
		offer(0, o);
	}
	
	public void drawShape(GL10 gl, int mode) {
		gl.glPushMatrix();
		
		gl.glVertexPointer(dimensions, GL10.GL_FLOAT, 0, buffer);
		//Draw second half
		if (secondHalfSize > 0) {
			gl.glDrawArrays(mode, splitPoint+gap, secondHalfSize);
		}
		
		//Draw first half of shape
		if (splitPoint > 0) {
			gl.glDrawArrays(mode, 0, splitPoint);
			gl.glDrawArrays(mode, splitPoint+gap+secondHalfSize-continuingVerts, continuingVerts*2);
		}
		
		gl.glPopMatrix();
	}
}
